﻿using Framework.ExtensionsMods.Util;
using NCrontab;

namespace Framework.ExtensionsMods.Test
{
	/// <summary>
	/// BackgroundService 方式实现简单的定时任务
	/// </summary>
	public class Worker : BackgroundService
	{
		private readonly CrontabSchedule _crontab;
		public Worker(ILogger<Worker> logger)
		{
			// 使用Crontab设定任务间隔
			_crontab = CrontabSchedule.Parse("0,30 * * * * *",
				new CrontabSchedule.ParseOptions
				{
					IncludingSeconds = true
				});
		}

		
		protected override async Task ExecuteAsync(CancellationToken stoppingToken)
		{
			
			while (!stoppingToken.IsCancellationRequested)
			{
				// 你的业务代码写到这里面
				Console.WriteLine(DateTime.Now);

				// 延迟 指定时间间隔
				await Task.Delay(CrontabScheduleUtil.GetSleepTimeSpan(_crontab.GetNextOccurrence(DateTime.Now)), stoppingToken);
			}
		}

	}
}